package com.marisfrolg.scanner.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.os.Environment;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

public class CodebarBuilder {
	/**
	 * 创建条形码的方法
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Bitmap createOneQRCode(String content, int w, int h)
			throws Exception {
		// 生成一维条码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.CODE_128, w, h);
		// 矩阵的宽度
		int width = matrix.getWidth();
		// 矩阵的高度
		int height = matrix.getHeight();
		// 矩阵像素数组
		int[] pixels = new int[width * height];
		// 双重循环遍历每一个矩阵点
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					// 设置矩阵像素点的值
					pixels[y * width + x] = 0xff000000;
				} else {
					pixels[y * width + x] = 0xffffffff;
				}
			}
		}
		// 根据颜色数组来创建位图
		/**
		 * 此函数创建位图的过程可以简单概括为为:更加width和height创建空位图，
		 * 然后用指定的颜色数组colors来从左到右从上至下一次填充颜色。 config是一个枚举，可以用它来指定位图“质量”。
		 */
		Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bm.setPixels(pixels, 0, width, 0, 0, width, height);
		// 将生成的条形码返回给调用者
		return bm;
	}

	/**
	 * 创建二维码的方法
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Bitmap createTwoQRCode(String content) throws Exception {
		// 生成二维码,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = new MultiFormatWriter().encode(content,
				BarcodeFormat.QR_CODE, 300, 300);
		// 矩阵的宽度
		int width = matrix.getWidth();
		// 矩阵的高度
		int height = matrix.getHeight();
		// 矩阵像素数组
		int[] pixels = new int[width * height];
		// 双重循环遍历每一个矩阵点
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					// 设置矩阵像素点的值
					pixels[y * width + x] = 0xff000000;
				}
			}
		}
		// 根据颜色数组来创建位图
		/**
		 * 此函数创建位图的过程可以简单概括为为:更加width和height创建空位图，
		 * 然后用指定的颜色数组colors来从左到右从上至下一次填充颜色。 config是一个枚举，可以用它来指定位图“质量”。
		 */
		Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bm.setPixels(pixels, 0, width, 0, 0, width, height);
		// 将生成的条形码返回给调用者
		return bm;
	}

	public static BarcodeFormat barcodeFormat = BarcodeFormat.CODE_128;

	public static Bitmap creatBarcode(Context context, String contents,
			int desiredWidth, int desiredHeight, boolean displayCode,
			int barType) {
		Bitmap ruseltBitmap = null;
		if (barType == 1)
			barcodeFormat = BarcodeFormat.CODE_128;
		else if (barType == 2)
			barcodeFormat = BarcodeFormat.QR_CODE;

		if (displayCode) {
			Bitmap barcodeBitmap = null;
			try {
				barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,desiredWidth, desiredHeight);
			} catch (WriterException e) {
				e.printStackTrace();
			}
			Bitmap codeBitmap = creatCodeBitmap(contents, desiredWidth,
					desiredHeight, context);
			ruseltBitmap = mixtureBitmap(barcodeBitmap, codeBitmap, new PointF(
					0.0F, desiredHeight));
		} else {
			try {
				ruseltBitmap = encodeAsBitmap(contents, barcodeFormat,
						desiredWidth, desiredHeight);
			} catch (WriterException e) {
				e.printStackTrace();
			}
		}

		return ruseltBitmap;
	}

	public static Bitmap creatCodeBitmap(String contents, int width,
			int height, Context context) {
		TextView tv = new TextView(context);
		LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
				width, height);
		tv.setLayoutParams(layoutParams);
		tv.setText(contents);
		tv.setHeight(48);
		tv.setTextSize(15.0F);
		tv.setGravity(1);
		tv.setWidth(width);
		tv.setDrawingCacheEnabled(true);
		tv.setTextColor(-16777216);
		tv.setBackgroundColor(-1);
		tv.measure(View.MeasureSpec.makeMeasureSpec(0, 0),
				View.MeasureSpec.makeMeasureSpec(0, 0));
		tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());

		tv.buildDrawingCache();
		Bitmap bitmapCode = tv.getDrawingCache();
		return bitmapCode;
	}

	public static Bitmap encode2dAsBitmap(String contents, int desiredWidth,
			int desiredHeight, int barType) {
		if (barType == 1)
			barcodeFormat = BarcodeFormat.CODE_128;
		else if (barType == 2)
			barcodeFormat = BarcodeFormat.QR_CODE;

		Bitmap barcodeBitmap = null;
		try {
			barcodeBitmap = encodeAsBitmap(contents, barcodeFormat,
					desiredWidth, desiredHeight);
		} catch (WriterException e) {
			e.printStackTrace();
		}
		return barcodeBitmap;
	}

	public static Bitmap mixtureBitmap(Bitmap first, Bitmap second,
			PointF fromPoint) {
		if ((first == null) || (second == null) || (fromPoint == null)) {
			return null;
		}

		Bitmap newBitmap = Bitmap.createBitmap(first.getWidth(),first.getHeight() + second.getHeight(),Bitmap.Config.ARGB_4444);
		Canvas cv = new Canvas(newBitmap);
		cv.drawBitmap(first, 0.0F, 0.0F, null);
		cv.drawBitmap(second, fromPoint.x, fromPoint.y, null);
		cv.save(31);
		cv.restore();

		return newBitmap;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Bitmap encodeAsBitmap(String contents, BarcodeFormat format,
			int desiredWidth, int desiredHeight) throws WriterException {
		int WHITE = -1;
		int BLACK = -16777216;

		HashMap hints = null;
		String encoding = guessAppropriateEncoding(contents);
		if (encoding != null) {
			hints = new HashMap(2);
			hints.put(EncodeHintType.CHARACTER_SET, encoding);
		}
		MultiFormatWriter writer = new MultiFormatWriter();
		BitMatrix result = writer.encode(contents, format, desiredWidth,desiredHeight, hints);
		int width = result.getWidth();
		int height = result.getHeight();
		int[] pixels = new int[width * height];

		for (int y = 0; y < height; ++y) {
			int offset = y * width;
			for (int x = 0; x < width; ++x){
				pixels[(offset + x)] = ((result.get(x, y)) ? BLACK : WHITE);
			}
		}

		Bitmap bitmap = Bitmap.createBitmap(width, height,Bitmap.Config.ARGB_8888);
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}

	public static String guessAppropriateEncoding(CharSequence contents) {
		for (int i = 0; i < contents.length(); ++i)
			if (contents.charAt(i) > 255)
				return "UTF-8";

		return null;
	}

	public static boolean saveBitmap2file(Bitmap bmp, String filename) {
		Bitmap.CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 100;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+ filename);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return bmp.compress(format, quality, stream);
	}

}
